<template>
  <div class="login h-full w-full flex-center">
    <NstdCard class="w-400px">
      <template #header>
        <div class="text-center text-18px">{{ appName }}</div>
      </template>
      <NstdForm class="login-form" :model="loginForm" ref="loginFormRef" :rules="loginFormRules" label-width="100px">
        <NstdFormItem class="form-item" label="用户名：" prop="userName">
          <NstdInput type="text" v-model="loginForm.userName" @keypress.enter="handlerLogin" />
        </NstdFormItem>
        <NstdFormItem label="密码：" prop="password">
          <NstdInput type="password" v-model="loginForm.password" @keypress.enter="handlerLogin" />
        </NstdFormItem>
      </NstdForm>
      <div class="flex-center">
        <NstdButton class="w-80%" auto-insert-space :loading="loginButtonLoading" type="primary" @click="handlerLogin">
          登录
        </NstdButton>
      </div>
    </NstdCard>
  </div>
</template>
<script setup>
import JSEncrypt from 'jsencrypt';
import { tagsStore, useAppStore, useAuthStore } from '@/stores';
import { NstdMessage } from 'nstd-components-pc-v3';
import { postSignV2Login, getClientMenuTreeByRoleAndApplication } from '@/api/auth/signV2.js';
import { sm2 } from 'sm-crypto';
const router = useRouter();
const app = useAppStore();
const auth = useAuthStore();
const loginFormRef = ref();
const loginButtonLoading = ref(false);
const loginFormRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};
const loginForm = reactive({
  loginType: 'pc',
  userName: '',
  password: ''
});
const appName = computed(() => {
  return window.NC_PROJECT_CONFIG.title
})

// 密码加密
// eslint-disable-next-line no-unused-vars
const encryptSingle = (value) => {
  const publicKey =
      'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQdPn6+Dy0m7fpsvqF/79Uhmo2HneV1Ee40Bx2rk8FtocEz6YxbSr4I4k2WKEr+7Zker9jYgjJMISF3lmH5wnGealTbp1ADSTzto8dLhMYogxfhnJSbk5TjYPFtNDOE7JMMpaW9ZhOkknozfUgZ+s9mVsecUosN31dUimN3D+woQIDAQAB';
  if (value) {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(value);
  }
  return '';
};
// 密码加密
const encryptSingle2 = (value) => {
  const publicKey = '025f735e103ee29ac7948d1c2d3cb32cea6a2b4cd1401adab89087d7076e0f57fe';
  const slot = 'NcSgcc@2017.';
  if (value) {
    const res = sm2.doEncrypt(slot + value, publicKey, 1);
    return `04${res}`;
  } else {
    return '';
  }
};

const validateLoginForm = async () => {
  try {
    const validateResult = await loginFormRef.value.validate();
    if (validateResult === true) {
      return true;
    }
  } catch (e) {
    console.log(e);
  }
  return false;
};
async function handlerLogin() {
  const validateResult = await validateLoginForm();
  if (validateResult) {
    loginButtonLoading.value = true;
    try {
      const bodyData = {
        ...loginForm,
        password: encryptSingle2(loginForm.password)
      };
      const { data, code, msg } = await postSignV2Login(bodyData);
      if (code === 200) {
        loginButtonLoading.value = false;
        auth.setUserInfo(data);
        console.log(data, 'data');
        NstdMessage.success('登录成功');
        getClientMenuTreeByRoleAndApplication({
          application: window.NC_PROJECT_CONFIG.application,
          projectName: window.NC_PROJECT_CONFIG.projectName,
          roleId: data.roleId
        }).then(async (res) => {
          if (res.data.length) {
            await router.push({ path: res.data[0].children[0].menuUrl });
            const navItem = {
              path: res.data[0].children[0].menuUrl,
              title: res.data[0].children[0].menuName,
              affix: '1',
              display: 1
            };
            // sessionStorage.setItem('navItem', JSON.stringify(navItem))
            const auth = tagsStore();
            auth.setNavList(navItem, { title: '' });
            const appType = window.NC_PROJECT_CONFIG.appType
            await router.push({ path: appType === 'pc' ? '/pcHome' : appType === 'monitor' ? '/monitorHome' : '/home' });
            // await router.push({ path: '/home' });
          }
          // await router.push({ path: '/' });
        });
      } else {
        NstdMessage.error(msg);
      }
    } catch (e) {
      NstdMessage.error(e?.msg || e?.message || '登录失败');
    } finally {
      loginButtonLoading.value = false;
    }
  }
}
</script>

<style lang="scss" scoped></style>
